package com.mvc.base.web;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import com.mvc.base.model.Picture;
import com.mvc.base.service.PictureManager;
import com.mvc.component.file.FileManager;
import com.mvc.framework.util.AjaxUtils;
import com.mvc.framework.util.FileUpDownUtils;
import com.mvc.framework.util.UploadFile;
import com.mvc.framework.web.FrameworkFactory;

/**
 * 
 * @author snowpbx
 * @version V1.0 Create Time: 2012-11-1
 */
@Controller
@RequestMapping("picture")
public class PictureController {

	@Autowired
	private PictureManager	pictureManager;

	@RequestMapping("upload/{type}/{itemId}")
	public String upload(@PathVariable Integer itemId, @PathVariable Integer type, HttpServletRequest request, ModelMap modelMap,
	        HttpServletResponse response) throws Exception {
		UploadFile uploadFile = FileUpDownUtils.getUploadFile(request, "qqfile");
		FileManager fileManager = FrameworkFactory.getFileManager();
		Long fileId = fileManager.saveFile(uploadFile.getFile());
		Picture picture = new Picture();
		picture.setItemId(itemId);
		picture.setType(type);
		picture.setFileId(fileId);
		picture.setFileName(uploadFile.getFileName());
		pictureManager.save(picture);
		modelMap.addAttribute("success", true);
		modelMap.addAttribute("fileSuffix", picture.getFileSuffix());
		modelMap.addAttribute("fileId", fileId + "");
		modelMap.addAttribute("fileName", uploadFile.getFileName());
		String message = "{\"success\":\"true\",\"fileSuffix\":\"" + picture.getFileSuffix() + "\",\"fileId\":\"" + fileId
		        + "\",\"fileName\":\"" + uploadFile.getFileName() + "\"}";
		AjaxUtils.doJsonResponse(response, message);
		return null;
	}

	@RequestMapping("delete/{fileId}")
	public String upload(@PathVariable Long fileId, ModelMap modelMap) throws Exception {
		FileManager fileManager = FrameworkFactory.getFileManager();
		fileManager.deleteFile(fileId);
		pictureManager.deleteByFileId(fileId);
		modelMap.addAttribute("success", true);
		return "jsonView";
	}

	@RequestMapping("update/{fileId}")
	public String update(@PathVariable Long fileId, String remark, ModelMap modelMap) throws Exception {
		if (fileId != null) {
			pictureManager.updateFileRemark(fileId, remark);
		}
		modelMap.addAttribute("success", true);
		return "jsonView";
	}

}
